//
//  Background.m (Level 1)
//  GameProject
//
//  Created by Blair Trusler on 21/07/2011.
//  Copyright Blair Trusler 2011. All rights reserved.
//


#import "GameHeader.h"

@implementation Background

@synthesize tileMap = _tileMap;
@synthesize background = _background;
@synthesize foreground = _foreground;
@synthesize meta = _meta;
@synthesize player = _player;
@synthesize playerSprite = _playerSprite;
@synthesize hud = _hud;
@synthesize allowDiags;
@synthesize startX,startY,endX,endY;

#pragma mark - dealloc
//Release retained objects
- (void) dealloc{
	self.tileMap = nil;
    self.background = nil;
    self.foreground = nil;
    self.player = nil;  
    self.playerSprite = nil;
    self.hud = nil;
//    [spotLight release];
//    [renderLayer release];
    
    [[SimpleAudioEngine sharedEngine] unloadEffect:@"level1Music.wav"];
	[super dealloc];
}

#pragma mark - scene
+(id) scene{
    //Create scene
	CCScene *scene = [CCScene node];
    
    //Add layer
	Background *layer = [Background node];
    
	//Add layer as a child of scene
	[scene addChild: layer z:0];      

    //Add HUD to scene
    HUD *hud = [HUD node];    
    [scene addChild: hud z:2];
    layer.hud = hud;   
    
	return scene;
}

#pragma mark initialize
-(id) init{
	if( (self=[super init] )) {
        direction = 0;
        isMoving = FALSE;
        
        //Disable touch input on this layer:
        self.isTouchEnabled = NO;

        
        if (dPadOn == FALSE){
            //Accelerometer enabled:
            self.isAccelerometerEnabled = YES;
            //Interval at which the hardware delivers the data:
            [[UIAccelerometer sharedAccelerometer] setUpdateInterval: (1.0 / 60)];
        }        
        else {
            self.isAccelerometerEnabled = NO; 
        }
        
        //Enable Music:
        [AudioManager playLevel1Music];
        
        //Initialize sprite sheet and batch node with .plist and .png files:
        [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"GameSpriteSheet.plist"]; 
        sceneSpriteBatchNode = [CCSpriteBatchNode batchNodeWithFile:@"GameSpriteSheet.png"];  
        
        //Add sprite nodes to background layer: 
        [self addChild:sceneSpriteBatchNode];
        //Load .TMX tiled map //and player sprite//
        [self loadMap];
        
        speedBoost = 0;     //Reset speed booster to 0
        speedBoostTilt = 0;
        
        //disable diagonal movement:
        self.allowDiags = NO; 

        if (([platformType isEqualToString:@"Simulator"])||([platformType isEqualToString:@"iPad"])||([platformType isEqualToString:@"iPad 2 (WiFi)"])||([platformType isEqualToString:@"iPad 2 (GSM)"])||([platformType isEqualToString:@"iPad 2 (CDMA)"])){
            CCLOG(@"Enabling Lighting");

        }
        
        //Schedule update method (for collision/warp detection)
        [self scheduleUpdate];
        
        //Schedule pathfinder every 1.5 seconds:
        [self schedule:@selector(createPath:) interval:3];  //using zero for the interval will just sync us with the default refresh, usually every 1/60 second

        CCLOG(@"Update Methods Scheduled");        
    }
    return self;
}


- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    int kPlayerSpeed = 2;
    float destX, destY;
    BOOL shouldMove = NO;
    float currentX = playerX.position.x;
    float currentY = playerX.position.y;
    oldPosition = ccp(playerX.position.x, playerX.position.y);    
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        
        if(acceleration.x > -0.40 ) {             // tilting the device upwards, move up
            isMoving = TRUE;
            destX = currentX ;
            destY = currentY + (kPlayerSpeed + speedBoostTilt);
            //        [playerX changeState:kStateWalkingUp];
            if (playerX.characterState != kStateCollision){
                //            [playerX changeState:kStateWalkingUp];
                direction = 1;
                shouldMove = YES;
            }
            else{
                shouldMove = NO;
            }        
        } 
        else if (acceleration.x < -0.60) {    // tilting the device down, move down
            isMoving = TRUE;
            destX = currentX ;
            destY = currentY - ( kPlayerSpeed + speedBoostTilt  );
            //        [playerX changeState:kStateWalkingDown];
            if (playerX.characterState != kStateCollision){
                //            [playerX changeState:kStateWalkingDown];
                direction = 2;
                shouldMove = YES;
            }
            else{
                shouldMove = NO;
            }        
        } 
        else if(acceleration.y < -0.05) {     // tilting the device to the right, move right
            isMoving = TRUE;
            destX = currentX + ( kPlayerSpeed + speedBoostTilt);
            destY = currentY ;
            //        [playerX changeState:kStateWalkingRight];
            if (playerX.characterState != kStateCollision){
                //            [playerX changeState:kStateWalkingRight];
                direction = 3;
                shouldMove = YES;
            }
            else{
                shouldMove = NO;
            }        
        } 
        else if (acceleration.y > 0.05) {     // tilting the device to the left, move left
            isMoving = TRUE;
            destX = currentX - (kPlayerSpeed + speedBoostTilt);
            destY = currentY ;
            //        [playerX changeState:kStateWalkingLeft];
            if (playerX.characterState != kStateCollision){
                //            [playerX changeState:kStateWalkingLeft];
                direction = 4;
                shouldMove = YES;
            }
            else{
                shouldMove = NO;
            }  
        } 
        
        else {
            destX = currentX;
            destY = currentY;
            shouldMove = NO;
            isMoving = FALSE;
        }
        if(shouldMove) {
            [playerX setPosition:CGPointMake(destX,destY)];
        }
        else {
            // should stop
            [playerX changeState:kStateIdle];
            direction = 0;
        }
    }
    else{
        if(acceleration.x > -0.40 ) {             // tilting the device upwards, move up
            isMoving = TRUE;
            destX = currentX ;
            destY = currentY + (kPlayerSpeed + speedBoostTilt);
            //        [playerX changeState:kStateWalkingUp];
            if (playerX.characterState != kStateCollision){
                //            [playerX changeState:kStateWalkingUp];
                direction = 1;
                shouldMove = YES;
            }
            else{
                shouldMove = NO;
            }        
        } 
        else if (acceleration.x < -0.60) {    // tilting the device down, move down
            isMoving = TRUE;
            destX = currentX ;
            destY = currentY - ( kPlayerSpeed + speedBoostTilt  );
            //        [playerX changeState:kStateWalkingDown];
            if (playerX.characterState != kStateCollision){
                //            [playerX changeState:kStateWalkingDown];
                direction = 2;
                shouldMove = YES;
            }
            else{
                shouldMove = NO;
            }        
        } 
        else if(acceleration.y < -0.15) {     // tilting the device to the right, move right
            isMoving = TRUE;
            destX = currentX + ( kPlayerSpeed + speedBoostTilt);
            destY = currentY ;
            //        [playerX changeState:kStateWalkingRight];
            if (playerX.characterState != kStateCollision){
                //            [playerX changeState:kStateWalkingRight];
                direction = 3;
                shouldMove = YES;
            }
            else{
                shouldMove = NO;
            }        
        } 
        else if (acceleration.y > 0.15) {     // tilting the device to the left, move left
            isMoving = TRUE;
            destX = currentX - (kPlayerSpeed + speedBoostTilt);
            destY = currentY ;
            //        [playerX changeState:kStateWalkingLeft];
            if (playerX.characterState != kStateCollision){
                //            [playerX changeState:kStateWalkingLeft];
                direction = 4;
                shouldMove = YES;
            }
            else{
                shouldMove = NO;
            }  
        } 
        
        else {
            destX = currentX;
            destY = currentY;
            shouldMove = NO;
            isMoving = FALSE;
        }
        if(shouldMove) {
            [playerX setPosition:CGPointMake(destX,destY)];
        }
        else {
            // should stop
            [playerX changeState:kStateIdle];
            direction = 0;
        }
    }
    
}



#pragma mark - camera
//Set camera on player position
//Developed with the help of Ray Wendlich Tutorial: http://www.raywenderlich.com/1163/how-to-make-a-tile-based-game-with-cocos2d
-(void)setViewpointCenter:(CGPoint) position {
    CGSize winSize = [[CCDirector sharedDirector] winSize];
    int x = MAX(position.x, winSize.width / 2);
    int y = MAX(position.y, winSize.height / 2);
    x = MIN(x, (_tileMap.mapSize.width * _tileMap.tileSize.width) - winSize.width / 2);
    y = MIN(y, (_tileMap.mapSize.height * _tileMap.tileSize.height) - winSize.height/2);
    CGPoint actualPosition = ccp(x, y);
    
    CGPoint centerOfView = ccp(winSize.width/2, winSize.height/2);
    CGPoint viewPoint = ccpSub(centerOfView, actualPosition);
    self.position = viewPoint;       
}


#pragma mark - map
//Generates game map, spawn positions and initiates path start and end points
//Developed with the help of Ray Wendlich Tutorial: http://www.raywenderlich.com/1163/how-to-make-a-tile-based-game-with-cocos2d
-(void)loadMap{
    CCLOG(@"Loading Tiled Map...");     //CCLOG instead of "NSLog" - unlike NSLog, CCLOG does not run on "release" builds, hence improving performance. 
    
    NSString *mapname = [Background getDefaultLevel]; //Sets ".tmx" file name as string 
    
    [[CCDirector sharedDirector] setProjection:CCDirectorProjection2D];     //Sets projection to 2D mode, removes bug with black lines/gaps between certain tiles when camera scrolling

    //Load .tmx file: 
    self.tileMap = [CCTMXTiledMap tiledMapWithTMXFile:mapname]; //Uses Level_1.tmx as level to load
    
    //Load map layers from tmx:
    self.background = [_tileMap layerNamed:@"Background"];
    self.foreground = [_tileMap layerNamed:@"Foreground"];  //Foreground items eg rocks, weapons etc
    self.meta = [_tileMap layerNamed:@"Meta"];              //Meta tiles determine whether object is obstacle or consumable
    _meta.visible = NO;                                     //Ensure meta tiles are hidden!
    
    CCTMXObjectGroup *objects = [_tileMap objectGroupNamed:@"Objects"];
    NSAssert(objects != nil, @"'Objects' object group not found");
    
    //Set up player spawn point
    NSMutableDictionary *spawnPoint = [objects objectNamed:@"SpawnPoint"];        
    NSAssert(spawnPoint != nil, @"SpawnPoint object not found");
    playerSpawnX = [[spawnPoint valueForKey:@"x"] intValue];
    playerSpawnY = [[spawnPoint valueForKey:@"y"] intValue];
    
    NSMutableDictionary *enemySpawn = [objects objectNamed:@"EnemySpawn"];        
    NSAssert(enemySpawn != nil, @"EnemySpawn object not found");
    enemySpawnX = [[enemySpawn valueForKey:@"x"] intValue];
    enemySpawnY = [[enemySpawn valueForKey:@"y"] intValue];
    enemySpawnPos1 = ccp(enemySpawnX,enemySpawnY);
        
    //Starting from enemy pos:
    CGPoint point = [self tileCoordForPosition:CGPointMake(enemySpawnX, enemySpawnY)];
	self.startX = point.x;
	self.startY = point.y;
    
    //To player pos:
    CGPoint point1 = [self tileCoordForPosition:CGPointMake(playerSpawnX, playerSpawnY)];
	self.endX = point1.x;
	self.endY = point1.y;
    
    for (int c = 0; c < TILE_COLS; c++) {
        for (int r = 0; r < TILE_ROWS; r++) {
            if (c == self.startX && r == self.startY) {
				tileArray[c][r] = TILE_START;
				CCLOG(@"Enemy Sprite Pos: %d, %d", c, r);
			}
            else if (c == self.endX && r == self.endY) {
				CCLOG(@"Player Pos: at %d, %d", c, r);
				tileArray[c][r] = TILE_FINISH;
			}
			else if ([self isWall:[self tilePositionForCoord:CGPointMake((float) c, (float) r)]]) {
				tileArray[c][r] = TILE_WALL;
			}
			else {
				tileArray[c][r] = TILE_OPEN;
			}
        }
    }
    [self addChild:_tileMap z:-100 tag:99];
    
    CCLOG(@"Tiled Map Loaded.");
}


#pragma mark get level
//Sets default level to load in the init class - will be the first game level. Currently test map for dev purposes. 
+(NSString*) getDefaultLevel{
    return @"Level_1.tmx";  //replace with "level 1" etc
}

#pragma mark - positions
- (CGPoint)tileCoordForPosition:(CGPoint)position {
    int x = position.x / _tileMap.tileSize.width;
    int y = ((_tileMap.mapSize.height * _tileMap.tileSize.height) - position.y) / _tileMap.tileSize.height;
    return ccp(x, y);
}

- (CGPoint)positionForTileCoord:(CGPoint)tileCoord {
    int x = (tileCoord.x * _tileMap.tileSize.width) + _tileMap.tileSize.width/2;
    int y = (_tileMap.mapSize.height * _tileMap.tileSize.height) - (tileCoord.y * _tileMap.tileSize.height) - _tileMap.tileSize.height/2;
    return ccp(x, y);
}

- (CGPoint)tilePositionForCoord:(CGPoint)coord {
    int x = (coord.x * _tileMap.tileSize.width) + (_tileMap.tileSize.width / 2);
    int y = (coord.y * _tileMap.tileSize.height) + (_tileMap.tileSize.height / 2);
    return ccp(x, y);
}

// Determines if the cell at the given position on the tilemap is a wall
-(BOOL) isWall:(CGPoint) position {
	CGPoint tileCoord = [self tileCoordForPosition:position];
	int tileGid = [_meta tileGIDAt:tileCoord];
	if (tileGid) {
        //tileMap not _tileMap??????
		NSDictionary *properties = [_tileMap propertiesForGID:tileGid];
		if (properties) {
			NSString *propertyValue = [properties valueForKey:@"Collidable"];
			if (propertyValue && [propertyValue compare:@"True"] == NSOrderedSame) {
				return YES;
			}
		}
	}
	return NO;
}


//Flip tile array
-(void) flipTileArray {
	unsigned char temp[TILE_COLS][TILE_ROWS]; 
    
	int destRow = TILE_ROWS-1;
	int srcRow = 0;
	
	//Store the original values in a temp array
	while (destRow >= 0) {
		for (int x = 0; x < TILE_COLS; x++) {
			temp[x][destRow] = tileArray[x][srcRow];
		}
		srcRow++;
		destRow--;
	}
    
	//Flip them
	for (int r = 0; r < TILE_ROWS; r++) {
		for (int c = 0; c < TILE_COLS; c++) {
			tileArray[c][r] = temp[c][r];
		}
	}
}

#pragma mark create path
//Generate path between player and enemy and move enemy sprite along path
-(void) createPath:(ccTime)dt {
	// Clear any old results;
	[self clear:nil];
	
	// Flip the tileArray (path algorithm expects origin to be upper left)
	[self flipTileArray];
	
	// Find the path
	BOOL pathFound = [self findPath: self.startX :self.startY :self.endX :self.endY]; 

	//Flip tileArray back so when we draw the path the objects will be in the correct location on the map
	[self flipTileArray];
    
    //If a path is detected between the sprites, move enemy sprite along the path
	if (pathFound) {
        [self moveOnPath];    
	}
    //If a path is not found, set enemy sprite state to idle to stop animation and return, wait until path can be detected 
	else {
		CCLOG(@"Path NOT found!!!");
        [enemy1 changeState:kStateIdle];   
        return;    
	}

}

-(void)moveOnPath{
    //If movement arrays are empty, return:
    if ([movementPathX count]<=1){ 
        CCLOG(@"Enemy movement arrays empty");
        [enemy1 changeState:kStateIdle];
        return; 
    }
    
    //Reverse order of contents in Arrays:
    NSUInteger i = 0;
    NSUInteger j = [movementPathX count] - 1;
    while (i < j) {
        [movementPathX exchangeObjectAtIndex:i withObjectAtIndex:j];
        [movementPathY exchangeObjectAtIndex:i withObjectAtIndex:j];
        i++;
        j--;
    }
    
    int x1,y1;  //For next position co-ords
    int x2,y2;  //For next tile check
    int x3,y3;  //For next, next tile check
    id moveAction, moveAction2, moveAction3;
    CCAction *walkingAction;

    for (int x = 0; x<1; x++){ 
        if ([movementPathX count]==2){  //Move at hop of 2
            x1=[[movementPathX objectAtIndex:x]intValue];
            y1=[[movementPathY objectAtIndex:x]intValue];
            moveAction = [CCMoveTo actionWithDuration:1.5 position:[self positionForTileCoord:CGPointMake((float) x1, (float) y1)]];
            
            x2=[[movementPathX objectAtIndex:x+1]intValue];
            y2=[[movementPathY objectAtIndex:x+1]intValue];
            moveAction2 = [CCMoveTo actionWithDuration:1.5 position:[self positionForTileCoord:CGPointMake((float) x2, (float) y2)]];
            
            walkingAction = [CCSequence actions:moveAction,moveAction2, nil]; 
            
        }
        
        if ([movementPathX count]>=3){  //Move at hop of 3
            x1=[[movementPathX objectAtIndex:x]intValue];
            y1=[[movementPathY objectAtIndex:x]intValue];
            moveAction = [CCMoveTo actionWithDuration:1.0 position:[self positionForTileCoord:CGPointMake((float) x1, (float) y1)]];
            
            x2=[[movementPathX objectAtIndex:x+1]intValue];
            y2=[[movementPathY objectAtIndex:x+1]intValue];
            moveAction2 = [CCMoveTo actionWithDuration:1.0 position:[self positionForTileCoord:CGPointMake((float) x2, (float) y2)]];
            
            x3=[[movementPathX objectAtIndex:x+2]intValue];
            y3=[[movementPathY objectAtIndex:x+2]intValue];
            moveAction3 = [CCMoveTo actionWithDuration:1.0 position:[self positionForTileCoord:CGPointMake((float) x3, (float) y3)]];
            
            walkingAction = [CCSequence actions:moveAction,moveAction2, moveAction3, nil];  
            
        }
    
        //Change direction of enemy sprite
        if (x1>x2){
            [enemy1 changeState:kStateWalkingLeft];
        }
        
        else if (x1<x2){
            [enemy1 changeState:kStateWalkingRight];
            
        }
        
        else if (y1>y2){
            [enemy1 changeState:kStateWalkingUp];
        }
        
        else if (y1<y2){
            [enemy1 changeState:kStateWalkingDown];
        }
                
        [enemy1 runAction:walkingAction];
    }
}

//Unmark discovered cells in the array
-(void) clear:(id) sender {
	int x,y;
	for(x=0;x<TILE_COLS;x++) {
		for(y=0;y<TILE_ROWS;y++) {
			if(tileArray[x][y] == TILE_MARKED)
				tileArray[x][y] = TILE_OPEN;
		}
	}
	//Create an array of nodes we need to remove from the parent
	//Iterate the list and mark them
	NSMutableArray *nodesToCleanup = [[NSMutableArray alloc] initWithCapacity:50];
	//Flag them for removal
	for (CCNode *node in self.children) {
		if (node.tag == TILE_TAG) {
			[nodesToCleanup addObject:node];
		}
	}
	//Now remove nodes
	for (CCNode *node in nodesToCleanup) {
		[node removeFromParentAndCleanup:YES];
	}
}

//Return whether a space is blocked
-(BOOL)spaceIsBlocked:(int)x :(int)y; {
	if(tileArray[x][y] == TILE_WALL)
		return YES;
	else
		return NO;
}

//Find a given node in array with specific x,y val:
-(PathNode *)nodeInArray:(NSMutableArray *)a withX:(int)x Y:(int)y{
    NSEnumerator *e = [a objectEnumerator];
    PathNode *n;
    if(e){
		while((n = [e nextObject])) {
			if((n->nodeX == x) && (n->nodeY == y))
			{
				return n;
			}
        }
    }
    return nil;
}

//Calculates node in array with lowest cost
-(PathNode *)lowestCostNodeInArray:(NSMutableArray*)openList{
    PathNode *n, *lowest;
    lowest = nil;
    
    NSEnumerator *enumerator = [openList objectEnumerator];
    
    if (enumerator){
		while((n = [enumerator nextObject])) {
			if(lowest == nil)
			{
				lowest = n;
			}
            else
            {
                if (n->cost < lowest -> cost){
                    lowest = n;
                }
            }
        }
        return lowest;
    }
    return nil;
}

#pragma mark A* path finder
//A* Path Finder - detects path between enemy and player sprites whilst avoiding walls
//Developed using http://www.raywenderlich.com/4970/how-to-implement-a-pathfinding-with-cocos2d-tutorial, http://www.cocos2d-iphone.org/forum/topic/6828 
-(BOOL)findPath:(int)startingX :(int)startingY :(int)endingX :(int)endingY {    
	int x,y;
	int newX,newY;
	int currentX,currentY;	NSMutableArray *openList, *closedList;
    
    if ((startingX==endingX) && (startingY==endingY)){
        CCLOG(@"Already at destination!");
        return NO;
    }
    
    openList = [NSMutableArray array];
    closedList = [NSMutableArray array];
   
    movementPathX = [NSMutableArray array];
    movementPathY = [NSMutableArray array];
    
    PathNode *currentNode = nil;
    PathNode *aNode = nil;
    PathNode *startNode = [PathNode node];
    
    startNode->nodeX = startingX;
    startNode->nodeY = startingY;
    startNode->parentNode = nil;
    startNode->cost = 0;
    
    [openList addObject:startNode];

    while ([openList count]){
        currentNode = [self lowestCostNodeInArray:openList];
        
        if ((currentNode->nodeX == endingX) && (currentNode->nodeY == endingY)){    //Path has been found            
            //Trace the path:
            aNode = currentNode->parentNode;
            while(aNode->parentNode!=nil){
                tileArray[aNode->nodeX][aNode->nodeY] = TILE_MARKED;
                [movementPathX addObject:[NSNumber numberWithInteger:aNode->nodeX]];
                [movementPathY addObject:[NSNumber numberWithInteger:aNode->nodeY]];
                aNode = aNode->parentNode;                
            }
            return YES;
        }
        else{
            
            [closedList addObject:currentNode];
            [openList removeObject:currentNode];
            
            currentX = currentNode->nodeX;
            currentY = currentNode->nodeY;
            
            //Check all surrounding tiles:
			for(y=-1;y<=1;y++){
                newY = currentY+y;
				for(x=-1;x<=1;x++){
                    newX = currentX+x;
					if(y || x){
                        //Bounds check of map:
						if((newX>=0)&&(newY>=0)&&(newX<TILE_COLS)&&(newY<TILE_ROWS)){
                            //Prevent diagonal checks:
                            if ((!(y==-1 && x==-1) && !(y==-1 && x==1)&& !(y== 1 && x== -1) && !(y==1 && x==1)) || self.allowDiags == YES) {
                                if(![self nodeInArray: openList withX: newX Y:newY]){
                                    if(![self nodeInArray: closedList withX: newX Y:newY])
									{
										if(![self spaceIsBlocked: newX :newY])
										{
                                            aNode = [PathNode node];
											aNode->nodeX = newX;
											aNode->nodeY = newY;
											aNode->parentNode = currentNode;
											aNode->cost = currentNode->cost + 1;
                                            
                                            //Compute cost:
                                            aNode->cost += (abs((newX) - endingX) + abs((newY) - endingY));
                                                                                        
                                            [openList addObject: aNode];
                                            
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return NO;
}


//Update Method
//Constantly checks for collisions/warps 
//Maintains camera focused on player sprite position
//Checks whether start/end points of path have changed
#pragma mark - 
#pragma mark - update
-(void) update: (ccTime)deltaTime{
    
    [self setViewpointCenter:playerX.position]; //constantly moves camera according to player position 
    if (([platformType isEqualToString:@"Simulator"])||([platformType isEqualToString:@"iPad"])||([platformType isEqualToString:@"iPad 2 (WiFi)"])||([platformType isEqualToString:@"iPad 2 (GSM)"])||([platformType isEqualToString:@"iPad 2 (CDMA)"])){
        fogCoord = [self convertToWorldSpace: ccp(playerX.position.x,playerX.position.y)];
    }

    //Updates player and enemy positions for path finder:
    CGPoint point = [self tileCoordForPosition:CGPointMake(enemy1.position.x, enemy1.position.y)];
	self.startX = point.x;
	self.startY = point.y;
    CGPoint point1 = [self tileCoordForPosition:CGPointMake(playerX.position.x, playerX.position.y)];
	self.endX = point1.x;
	self.endY = point1.y;
    
    //Constantly checking for obstacles/warps:
     tileCoord = [self tileCoordForPosition:playerX.position];
     tileCoord1 = [self tileCoordForPosition:enemy1.position];

    int tileGid = [_meta tileGIDAt:tileCoord];
    
    if (tileGid) {
        NSDictionary *properties = [_tileMap propertiesForGID:tileGid];
        if (properties) {
            //Collision
            NSString *collision = [properties valueForKey:@"Collidable"];

            if (collision && [collision compare:@"True"] == NSOrderedSame) {
                CCLOG(@"Collision (update method)");
//                [AudioManager collisionSound];
                [playerX changeState:kStateCollision];
                return;
            }
            //Warp - when player steps on "warp" meta tile, load new scene
            NSString *warp = [properties valueForKey:@"Warp"];
            if (warp && [warp compare:@"1"] == NSOrderedSame) {
                CCLOG(@"Level Complete! (WARP)");  
                [AudioManager levelComplete];
                [[SceneManager sharedSceneManager] runSceneWithID:kLevelCompleteScene];     //Objective reached, load "level complete" scene
                
            }
        }
    }
}

@end


